<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="profile-header">
          <h2>个人中心</h2>
          <p>管理您的个人资料和信息</p>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 基本资料标签页 -->
        <el-tab-pane label="基本资料" name="basic">
          <div class="profile-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="用户名">{{ userData.username }}</el-descriptions-item>
              <el-descriptions-item label="用户类型">
                <el-tag :type="userData.user_type === 'job_seeker' ? 'success' : 'primary'">
                  {{ userData.user_type === 'job_seeker' ? '求职者' : '招聘者' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ userData.email }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ userData.phone }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>





        <!-- 修改资料标签页 -->
        <el-tab-pane label="修改资料" name="edit">
          <el-form :model="editForm" label-width="100px" :rules="rules" ref="editFormRef">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="editForm.phone" />
            </el-form-item>

<!--            <template v-if="userData.user_type === 'job_seeker'">-->
<!--              <el-form-item label="当前状态">-->
<!--                <el-select v-model="editForm.current_status" placeholder="请选择">-->
<!--                  <el-option-->
<!--                    v-for="item in statusOptions"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                  />-->
<!--                </el-select>-->
<!--              </el-form-item>-->

<!--            </template>-->



            <el-form-item>
              <el-button type="primary" @click="submitEdit" :loading="loading">保存修改</el-button>
              <el-button @click="resetEditForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 修改密码标签页 -->
        <el-tab-pane label="修改密码" name="changePassword">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="passwordForm.currentPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmNewPassword">
              <el-input v-model="passwordForm.confirmNewPassword" type="password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitPasswordChange" :loading="loading">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref('basic')
const loading = ref(false)

// 用户数据
const userData = ref({
  username: '',
  user_type: '',
  email: '',
  phone: '',
  current_status: '',
  desired_position: '',
  company_name: ''
})

// 编辑表单
const editForm = ref({
  email: '',
  phone: '',
  current_status: '',
  desired_position: '',
  company_name: '',
  user_id:localStorage.getItem('user_id')
})

// 密码修改表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmNewPassword: ''
})

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],

}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
  confirmNewPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validatePasswordConfirm, trigger: 'blur' }
  ]
}

// 密码确认验证
function validatePasswordConfirm(rule, value, callback) {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 状态选项
const statusOptions = [
  { value: '在职-考虑机会', label: '在职-考虑机会' },
  { value: '离职-随时到岗', label: '离职-随时到岗' },
  { value: '在校学生', label: '在校学生' }
]

// 获取用户信息
const fetchUserData = async () => {
  try {
    loading.value = true;

    // 构建 URL 查询参数
    const userId = localStorage.getItem('user_id');
    if (!userId) {
      throw new Error('用户未登录');
    }
    const response = await fetch(`http://127.0.0.1:8000/api/user-info?user_id=${userId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取用户信息失败: ${errorText}`);
    }

    const data = await response.json();
    userData.value = data;

    // 初始化编辑表单
    editForm.value = {
      email: data.email,
      phone: data.phone
    };
  } catch (error) {
    ElMessage.error('获取用户信息失败');
    console.error(error);
    // router.push('/login');
  } finally {
    loading.value = false;
  }
}


// 提交编辑
const submitEdit = async () => {
  try {
    loading.value = true
    console.log('Request body:', JSON.stringify(editForm.value));
    console.log('Request headers:', {
    'Authorization': `Bearer ${localStorage.getItem('token')}`
    });
    const response = await fetch('http://127.0.0.1:8000/api/updateprofile', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        user_id: parseInt(localStorage.getItem('user_id')),
        email: editForm.value.email,
        phone: editForm.value.phone
      })
    })

    if (!response.ok) {
      throw new Error('更新失败')
    }

    ElMessage.success('资料更新成功')
    await fetchUserData() // 刷新数据
    activeTab.value = 'basic' // 返回基本信息标签页
  } catch (error) {
    ElMessage.error(error.message || '更新失败')
  } finally {
    loading.value = false
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editForm.value = {
    email: userData.value.email,
    phone: userData.value.phone,
    current_status: userData.value.current_status,
    desired_position: userData.value.desired_position,
    company_name: userData.value.company_name
  }
}

// 提交密码修改
const submitPasswordChange = async () => {
  try {
    loading.value = true
    const response = await fetch('http://127.0.0.1:8000/api/changepassword', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        user_id: parseInt(localStorage.getItem('user_id')),
        current_password: passwordForm.value.currentPassword,
        new_password: passwordForm.value.newPassword
      })
    })

    if (!response.ok) {
      throw new Error('密码修改失败')
    }

    ElMessage.success('密码修改成功')
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmNewPassword: ''
    }
    activeTab.value = 'basic' // 返回基本信息标签页
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取用户数据
onMounted(() => {
  fetchUserData()
})
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  padding: 40px 0;
  min-height: calc(100vh - 60px);
  //background-color: #f5f7fa;
}

.profile-card {
  width: 800px;
}

.profile-header {
  text-align: center;
}

.profile-header h2 {
  color: #409eff;
  margin-bottom: 10px;
}

.profile-header p {
  color: #909399;
  font-size: 14px;
}

.profile-info {
  padding: 20px;
}

.job-seeker-info, .recruiter-info {
  padding: 20px;
}

.el-descriptions {
  margin-top: 20px;
}

.el-tag {
  margin-right: 10px;
}
</style>